/**
 * 自定义Hook
 */

import React, {useState, useEffect} from "react";

function useFriendStatus(friendID) {
    const [isOnline, setIsOnline] = useState(null);

    function handleStatusChange(status) {
        console.log(status, `=========>status`)
        setIsOnline(status);
    }

    function mathRandomStatus() {
        return [null,true,false][parseInt(Math.random() * 3)]
    }

    useEffect(() => {
        const status = mathRandomStatus()
        handleStatusChange(status)
        // ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
        return () => {
            handleStatusChange(status)
            // ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
        };
    });

    return isOnline;
}

/**
 * 两个组件使用这个Hook
 */

function FriendStatus(props) {
    const isOnline = useFriendStatus(props.id);

    if (isOnline === null) {
        return 'Loading...';
    }
    return isOnline ? 'Online' : 'Offline';
}

function FriendListItem(props) {
    const isOnline = useFriendStatus(props.id);

    return (
        <li style={{ color: isOnline ? 'green' : 'black' }}>
            {props.name}
        </li>
    );
}

function getFriend() {
    return (
        <FriendStatus id={1} name={'aaa'}/>
    )
}
export default getFriend
